package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.ProductConstant;
import com.atguigu.common.to.SkuHasStockVo;
import com.atguigu.common.to.SkuReductionTo;
import com.atguigu.common.to.SpuBoundTo;
import com.atguigu.common.to.es.SkuEsModel;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.product.dao.SpuInfoDao;
import com.atguigu.gulimall.product.entity.*;
import com.atguigu.gulimall.product.feign.CouponFeignService;
import com.atguigu.gulimall.product.feign.SearchFeignService;
import com.atguigu.gulimall.product.feign.WareFeignService;
import com.atguigu.gulimall.product.service.*;
import com.atguigu.gulimall.product.vo.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {


    @Autowired
    CouponFeignService couponFeignService;

    @Autowired
    private SpuInfoDescService spuInfoDescService;
    @Autowired
    private SpuImagesService spuImagesService;
    @Autowired
    private SkuImagesService skuImagesService;
    @Autowired
    private SkuInfoService skuInfoService;
    @Autowired
    private AttrService attrService;
    @Autowired
    private ProductAttrValueService productAttrValueService;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    private BrandService brandService;  //品牌

    @Autowired
    private CategoryService CategoryService;


    @Autowired
    private WareFeignService wareFeignService;

    //上架商品

    @Autowired
    private SearchFeignService searchFeignService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 后台管理服务来提交增删改查数据、不需要超高的并发、提交成功就成功、失败就失败了
     *  这一块适合使用Seata分布式事务(AT模式)、后台管理系统简单的场景外、那如果是高并发场景外比如下单场景就不适合了
     *
     *   Seata(AT模式)做一个事务就会加超多的锁、一加锁相当于把并发变成了串行化、如果高并发起来、订单都这吗做、所有人都可能要等待上一订单下来、再来下下一个订单
     *              在高并发里面解决分布式事务：
     *                          不考虑：2PC模式
     *                                  TCC事务补偿型方案
     * @param spuSaveVo
     */

    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo spuSaveVo) {
        //1、保存spu基本信息 pms_spu_info
        SpuInfoEntity infoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuSaveVo, infoEntity);
        infoEntity.setCreateTime(new Date());
        infoEntity.setUpdateTime(new Date());
        this.saveBaseSpuInfo(infoEntity);

        //2、保存Spu的描述图片 pms_spu_info_desc
        List<String> decript = spuSaveVo.getDecript();
        SpuInfoDescEntity descEntity = new SpuInfoDescEntity();
        descEntity.setSpuId(infoEntity.getId());
        descEntity.setDecript(String.join(",", decript));
        spuInfoDescService.saveSpuInfoDesc(descEntity);

        //3、保存spu的图片集 pms_spu_images

        List<String> images = spuSaveVo.getImages();
        spuImagesService.saveImages(infoEntity.getId(), images);

        //4、保存spu的规格参数;pms_product_attr_value
        List<BaseAttrs> baseAttrs = spuSaveVo.getBaseAttrs();
        List<ProductAttrValueEntity> collect = baseAttrs.stream().map((e) -> {
            ProductAttrValueEntity attrValueEntity = new ProductAttrValueEntity();
            attrValueEntity.setAttrId(e.getAttrId());
            AttrEntity byId = attrService.getById(e.getAttrId());

            attrValueEntity.setAttrName(byId.getAttrName())
                    .setAttrValue(e.getAttrValues())
                    .setQuickShow(e.getShowDesc())
                    .setSpuId(infoEntity.getId());

            return attrValueEntity;

        }).collect(Collectors.toList());
        productAttrValueService.saveProductAttr(collect);

        //5、保存spu的积分信息；gulimall_sms->sms_spu_bounds
        Bounds bounds = spuSaveVo.getBounds();
        SpuBoundTo boundTo = new SpuBoundTo();
        BeanUtils.copyProperties(bounds, boundTo);
        boundTo.setSpuId(infoEntity.getId());

        R r1 = couponFeignService.saveSpuBounds(boundTo);
        if (r1.getCode() != 0) {
            log.error("远程保存spu积分信息");
        }


        //5、保存当前spu对应的所有sku信息；

        List<Skus> skus = spuSaveVo.getSkus();
        if (skus != null && skus.size() > 0) {
            skus.forEach(item -> {

                String defaultImg = "";
                for (Images image : item.getImages()) {
                    if (image.getDefaultImg() == 1) {
                        defaultImg = image.getImgUrl();

                    }
                }

                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(item, skuInfoEntity);
                skuInfoEntity.setBrandId(infoEntity.getBrandId());
                skuInfoEntity.setCatalogId(infoEntity.getCatalogId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSpuId(infoEntity.getId());
                skuInfoEntity.setSkuDefaultImg(defaultImg);

                //5.1）、sku的基本信息；pms_sku_info
                skuInfoService.saveSkuInfo(skuInfoEntity);
                Long skuId = skuInfoEntity.getSkuId();

                List<SkuImagesEntity> imagesEntity = item.getImages().stream().map((img) -> {
                    SkuImagesEntity skuimagesentity = new SkuImagesEntity()
                            .setSkuId(skuId)
                            .setImgUrl(img.getImgUrl())
                            .setDefaultImg(img.getDefaultImg());
                    return skuimagesentity;
                }).filter((entity) -> {
                    //返回true 就是需要，fase 就是剔除
                    return !StringUtils.isEmpty(entity.getImgUrl());
                }).collect(Collectors.toList());

                //5.2）、sku的图片信息；pms_sku_image
                skuImagesService.saveBatch(imagesEntity);


                //TODO 没有图片；路径无需保存
                //5.3）、sku的销售属性信息：pms_sku_sale_attr_value
                List<Attr> attr = item.getAttr();
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntity = attr.stream().map((e) -> {
                    SkuSaleAttrValueEntity entity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(e, entity);
                    entity.setSkuId(skuId);  //保存skuId
                    return entity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntity);


                // //5.4）、sku的优惠、满减等信息；gulimall_sms->sms_sku_ladder\sms_sku_full_reduction\sms_member_price
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(item, skuReductionTo);
                skuReductionTo.setSkuId(skuId);
                if (skuReductionTo.getFullCount() > 0 && skuReductionTo.getFullPrice().compareTo(new BigDecimal("0")) == 1) {
                    R r = couponFeignService.saveSkuReduction(skuReductionTo);
                    if (r.getCode() != 0) {
                        log.error("远程保存sku优惠信息失败");
                    }
                }

            });
        }


        //返回true就是需要，false就是剔除
        //TODO 没有图片路径的无需保存


    }

    public void saveBaseSpuInfo(SpuInfoEntity infoEntity) {

        this.baseMapper.insert(infoEntity);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();

        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            wrapper.and((w) -> {
                w.eq("id", key).or().like("spu_name", key);
            });
        }

        String status = (String) params.get("status");
        if (!StringUtils.isEmpty(status)) {
            wrapper.eq("publish_status", status);
        }
        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(brandId) && !"0".equalsIgnoreCase(brandId)) {
            wrapper.eq("brand_id", brandId);
        }

        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(catelogId) && !"0".equalsIgnoreCase(catelogId)) {
            wrapper.eq("catalog_id", catelogId);
        }


        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public void up(Long spuId) {
        //1、查出当前SpuId对应的所有sku信息，品牌的名字
        List<SkuInfoEntity> skus = skuInfoService.getSkuBySpuId(spuId);


        List<Long> skuIdList = skus.stream()
                .map(SkuInfoEntity::getSkuId)
                .collect(Collectors.toList());

        //TODO 4、查出当前sku的所有可以被用来检索的规格属性(所有属性的id)
        List<ProductAttrValueEntity> baseAttrs = productAttrValueService.baseAttrlistforspu(spuId);
        List<Long> attrIds = baseAttrs.stream().map((attr) -> {
            return attr.getAttrId();
        }).collect(Collectors.toList());


        //在指定的所有属性集合里面，挑出检索属性
        List<Long> searchAttrIds = attrService.selectSearchAttrIds(attrIds);
        Set<Long> idSet = new HashSet<>(searchAttrIds);

        //创建EsModel 里面的arrs的集合
        List<SkuEsModel.Attrs> attrValueEntities = baseAttrs.stream().filter(item -> {
            return idSet.contains(item.getAttrId());
        }).map(item -> {
            //把数据库查询的copy到esModel对象里面
            SkuEsModel.Attrs attrs1 = new SkuEsModel.Attrs();
            BeanUtils.copyProperties(item, attrs1);
            return attrs1;
        }).collect(Collectors.toList());


        Map<Long, Boolean> stoMap = null;
        try {
            R skuHasStock = wareFeignService.getSkuHasStock(skuIdList);
            TypeReference<List<SkuHasStockVo>> typeReference = new TypeReference<List<SkuHasStockVo>>() {
            };
            stoMap = skuHasStock.getDta(typeReference).stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, item ->
                    item.getHasStock()));
        } catch (Exception e) {
            log.error("库存服务查询异常{}", e);
        }

        //封装每个sku的信息
        Map<Long, Boolean> finalStoMap = stoMap;
        List<SkuEsModel> uoProducts = skus.stream().map(sku -> {
            //组装需要的数据
            SkuEsModel esModel = new SkuEsModel();
            BeanUtils.copyProperties(sku, esModel);
            esModel.setSkuPrice(sku.getPrice());
            esModel.setSkuImg(sku.getSkuDefaultImg());

            //设置库存信息
            if (finalStoMap == null) {
                esModel.setHasStock(true);
            } else {
                esModel.setHasStock(finalStoMap.get(sku.getSkuId()));
            }

            //TODO 1、发送远程调用，库存系统查询是否有库存（不需要查询库存有多少）

            //TODO 2、热度评分、默认为0
            esModel.setHotScore(0L);

            //TODO 3、查询品牌和分类的名字信息
            BrandEntity brandEntity = brandService.getById(esModel.getBrandId());
            esModel.setBrandName(brandEntity.getName());
            esModel.setBrandImg(brandEntity.getLogo());


            CategoryEntity categoryEntity = CategoryService.getById(esModel.getCatalogId());
            esModel.setCatalogName(categoryEntity.getName());

            //设置Attrs到 esModel
            esModel.setAttrs(attrValueEntities);
            return esModel;
        }).collect(Collectors.toList());

        //将数据发送到es进行保存 gulimall-search
        R r = searchFeignService.productStatusUp(uoProducts);
        if (r.getCode() == 0) {
            //远程调用成功  ----》修改上架的状态 ----》wms_ware_sku表
            baseMapper.updateSpuStatus(spuId, ProductConstant.StatusEnum.SPU_UP.getCode());
        } else {
            //远程调用失败
            // TODO 7、重复调用？ 接口幂等性；重试机制？ xxx
            /**
             * feign 调用流程
             * 1、构造请求数据，将对象转为json;
             *            RequestTemplate template = buildTemplateFromArgs.create(argv);
             * 2、发送请求进行执行(执行成功会解码响应数据)：
             *           executeAndDecode(template);
             * 3、执行请求会有重试机制(默认关闭的重试机制)
             *           while(true){
             *               try{
             *                    //1、如果有问题就走下面的重试机制
             *                   executeAndDecode(template);
             *               }catch(){
             *                 try{
             *                   //2、如果有异常会把异常抛出去
             *                   retryer.continueOrPropagate(e);
             *                       }catch(){
             *                          throw ex;
             *                          //3、如果没有异常就
             *                   }
             *                      continue;
             *                           //4、一continue 就又会到while(true) 开始执行
             *               }
             *           }
             */
        }
    }

    @Override
    public SpuInfoEntity getSpuInfoBySkuId(Long skuId) {
        //获取skuid的对象
        SkuInfoEntity byId = skuInfoService.getById(skuId);
        Long spuId = byId.getSpuId();

        SpuInfoEntity spuInfoEntity = getById(spuId);
        return spuInfoEntity;
    }


}
